package com.datang.pet.common.socket;
/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-05-10 12:22
 * @notify socket长链接
 * @version 1.0
 */


import com.alibaba.fastjson.JSON;
import com.datang.pet.common.utils.MD5;
import com.datang.pet.common.redis.RedisTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint(value = "/message")
@Component
public class WebSocketServer {

    //用来存储所有用的的连接session
    private static HashMap<String, Session> userSession = new HashMap<>();

    //redis工具
    private static RedisTool redisTool;

    @Autowired
    public void setRedisTool(RedisTool redisTool) {
        this.redisTool = redisTool;
    }

    /*
     * @author 顶风少年
     * @date 2019/6/9 16:07
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param message
     * @param session
     * @result void
     * @notify 接收客户端发送的消息
     * version 1.0
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        //将消息转换成json
        Map<String, String> ms = (Map) JSON.parse(message);
        //接收消息类型
        String type = ms.get("type");
        //接收消息内容
        String data = ms.get("data");
        //如果消息是给的id,则表示这个用户刚刚登陆,把用户id和session存到map中
        if (type.equals("sendId")) {
            //解密userid
            String userId = MD5.decryptData(data);
            //将用户id存入map
            userSession.put(userId, session);
            //将用户id存入redis 时效为5分钟
            redisTool.set(userId, userId, 300L);
        }
    }

    /*
     * @author 顶风少年
     * @date 2019/5/10 14:11
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param data
     * @param session
     * @result void
     * @notify 向服务端发送消息
     * version 1.0
     */
    public void sendMessage(String data, String id) throws Exception {
        //从map中获取 session
        Session session = userSession.get(id);
        RemoteEndpoint.Basic basicRemote = session.getBasicRemote();
        basicRemote.sendText(data);
    }


}
